package com.hanbang.chu_xing_gao_zhao.view_city_select;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.module.RegisterPerfectActivity;
import com.hanbang.chu_xing_gao_zhao.utils.JsonHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.view_city_select.MyViewSideBar.OnTouchingLetterChangedListener;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 选拔城市 视图
 * 
 * @author Administrator
 * 
 */
public class CitySelectActivity extends BaseActivity {
	public PinyinComparator comparator = new PinyinComparator();

	ArrayList<ItemCityData> listData = new ArrayList<ItemCityData>();
	/**
	 * 索引条
	 */
	private MyViewSideBar sideBar;
	private ListView listView;
	private SortAdapter adapter;
	/** 城市数据 */
	/**
	 * 中心提示
	 */
	private TextView dialogTxt;
	/**
	 * 搜索框
	 */
	private MyViewSearchEditText mSearchEditText;
	/** 城市数组 */
	private String[] city;

	;

	/**
	 * 中心提示
	 */
	private TextView buxian;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.me_addressed_city_activity);

		init();
		getCityData();
		addLitener();
		addListAdapter();

	}

	/**
	 * 得到城市列表
	 */
	private void getCityData() {

		try {
			if (dbUtils.count(ItemCityData.class) > 1) {
//				MyLog.i("text", "*EEE**" + dbUtils.count(ItemCityData.class));// *****
				listData = (ArrayList<ItemCityData>) dbUtils.findAll(ItemCityData.class);
				return;
			}

		} catch (DbException e1) {

			e1.printStackTrace();
		}


//		httpUtils.send(HttpMethod.GET, HttpInterfaces.GetCityList, new MyRequestCallBack<String>(this, "加载城市列表...") {
//			@Override
//			public void onSuccess(ResponseInfo<String> responseInfo) {
//				super.onSuccess(responseInfo);
//				try {
//					JSONObject json = new JSONObject(responseInfo.result);
//
//					int status = json.getInt("Result");
//					if (status == 0) {
//						JSONArray relate = json.getJSONArray("list");
//
//						// 把数据从接口解析出来
//						listData.addAll(JsonHelper.parseCollection(relate, ArrayList.class, ItemCityData.class));
//
//						// 保存之前把拼音添加上
//						addPinYin(listData);
//						// 保存到数据库
//						dbUtils.saveAllAutoThrows(listData);
//						// 更新适配器中的集合
//						adapter.list = listData;
//						// 更新适配器
//						adapter.notifyDataSetChanged();
//
//					} else {
//
//					}
//
//				} catch (JSONException e) {
//					e.printStackTrace();
//				}
//
//			}
//		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		finish();
	}

	@Override
	protected void onPause() {
		super.onPause();

	}

	/**
	 * listView 添加 adapter
	 */
	private void addListAdapter() {
		adapter = new SortAdapter(getApplicationContext(), listData);
		listView.setAdapter(adapter);
		
		// 保存之前把拼音添加上
		addPinYin(listData);
		
		// 更新适配器中的集合
		adapter.list = listData;
		// 更新适配器
		adapter.notifyDataSetChanged();

	}

	/**
	 * 初始化
	 */
	private void init() {

		sideBar = (MyViewSideBar) findViewById(R.id.sb_me_addressed_city);
		dialogTxt = (TextView) findViewById(R.id.tv_me_addressed_citytxt_dialog);
		sideBar.setmTextDialog(dialogTxt);
		mSearchEditText = (MyViewSearchEditText) findViewById(R.id.tv_me_addressed_city_search);
		city = getResources().getStringArray(R.array.city);
		buxian= (TextView) findViewById(R.id.buxian);
		buxian.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				/**
				 * 把选择的数据返回过去
				 */
				Intent intent = new Intent(CitySelectActivity.this, RegisterPerfectActivity.class);

				intent.putExtra("city", "不限");
				intent.putExtra("cityId", "0");

				setResult(RESULT_OK, intent);// 带有Bundle的intent，当然也可以自己定义新的Bundle
				finish();// 此处一定要调用finish()方法
			}
		});

	}

	/**
	 * 添加拼音并排序
	 */
	private void addPinYin(List<ItemCityData> data) {

		/**
		 * 往实体中添加数据,这里添加的都把中文转成拼音之后的
		 */
		try {
			filledData(data);
		} catch (BadHanyuPinyinOutputFormatCombination e1) {
			e1.printStackTrace();
		}
		/**
		 * 排序 sort by a-z
		 */
		Collections.sort(listData, comparator);

	}

	/**
	 * 添加监听
	 */
	private void addLitener() {

		// 索引条的监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			public void onTouchingLetterChanged(String str) {
				int position = adapter.getPositionForSection(str.charAt(0));
				if (position != -1)
					listView.setSelection(position);

			}
		});

		/**
		 * listView 设置
		 */
		listView = (ListView) findViewById(R.id.lv_me_addressed_city_listView);
		// 设置选中的背景，目前是透明的
		listView.setSelector(new ColorDrawable(Color.TRANSPARENT));

		listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Toast.makeText(getApplicationContext(), ((ItemCityData) adapter.getItem(position)).getCityName(),
						Toast.LENGTH_SHORT).show();
				/**
				 * 把选择的数据返回过去
				 */
				Intent intent = new Intent(CitySelectActivity.this, RegisterPerfectActivity.class);
				
				intent.putExtra("city", ((ItemCityData) adapter.getItem(position)).getCityName());
				intent.putExtra("cityId", String.valueOf(listData.get(position).getCityID()));

				setResult(RESULT_OK, intent);// 带有Bundle的intent，当然也可以自己定义新的Bundle
				finish();// 此处一定要调用finish()方法

			}
		});

		/**
		 * 搜索数据的过滤
		 */
		mSearchEditText.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence str, int arg1, int arg2, int arg3) {
				try {
					// 过滤数据
					filerData(str.toString());
				} catch (BadHanyuPinyinOutputFormatCombination e) {
					e.printStackTrace();
				}
			}

			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}

			public void afterTextChanged(Editable arg0) {
			}
		});

	}

	/**
	 * 添加数据
	 * 
	 * @param date
	 * @return
	 * @throws BadHanyuPinyinOutputFormatCombination
	 */
	private void filledData(List<ItemCityData> date) throws BadHanyuPinyinOutputFormatCombination {

		for (int i = 0; i < date.size(); i++) {
			ItemCityData itemCityData = date.get(i);

			// 汉字转换成拼音
			String pinyin = PinYinKit.getPingYin(date.get(i).getCityName());
			// 截取第一个字母并转成大写
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				itemCityData.setSortLetters(sortString.toUpperCase());
			} else {
				itemCityData.setSortLetters("#");
			}

		}

	}

	/**
	 * 搜索时过滤数据
	 * 
	 * @param str
	 * @throws BadHanyuPinyinOutputFormatCombination
	 */
	private void filerData(String str) throws BadHanyuPinyinOutputFormatCombination {
		List<ItemCityData> fSortModels = new ArrayList<ItemCityData>();
		/**
		 * 输入框内容不是空
		 */
		if (TextUtils.isEmpty(str))
			fSortModels = listData;
		else {
			// 不是空则先清楚
			fSortModels.clear();

			for (ItemCityData sortModel : listData) {
				String name = sortModel.getCityName();

				/**
				 * 首字母相同添加到集合
				 */
				if (sortModel.getSortLetters().equals(str.toUpperCase())) {
					fSortModels.add(sortModel);
				}

				/**
				 * 把name 转成char[]
				 */
				char[] c = name.toCharArray();
				/**
				 * 如果名字是中文开头，则进行后面文字的判断
				 */
				if ((int) c[1] > 500) {

					for (int i = 1; i < name.length(); i++) {
						/**
						 * 从名字的第二个字开始判断，首字母是不是与输入的对应
						 */
						if (PinYinKit.getPingYin(name.substring(i)).startsWith(str.toUpperCase())) {
							fSortModels.add(sortModel);
						}
					}
				}
			}
		}
		// 比较排序
		Collections.sort(fSortModels, comparator);
		// 更新adapter listview 数据源
		adapter.updateListView(fSortModels);
	}

	@Override
	protected void onResume() {
		setTitleMore(View.INVISIBLE, View.INVISIBLE, "城市选择", null, null, null);
		super.onResume();

	}

}
